﻿using M_Quality.API.Application.Command.ReinspectionCommand;
using M_Quality.Domain;
using M_Quality.Domain.Dto;
using M_Quality.Repository.Interface;
using MediatR;

namespace M_Quality.API.Application.CommandHandler.ReinspectionCommandHandler
{
    /// <summary>
    /// 显示复检信息
    /// </summary>
    public class ShowReinspectionCommandHandler : IRequestHandler<ShowReinspectionCommand, PageDto<Reinspection>>
    {
        private readonly IReinspectionRepository _Reinspectionrepository;
        public ShowReinspectionCommandHandler(IReinspectionRepository reinspectionrepository)
        {
            _Reinspectionrepository = reinspectionrepository;
        }
        public async Task<PageDto<Reinspection>> Handle(ShowReinspectionCommand request, CancellationToken cancellationToken)
        {
            var ReList = await _Reinspectionrepository.GetAsync(d => !d.IsDeleted);
            if (!string.IsNullOrEmpty(request.ReinspectionName))
            {
                ReList= ReList.Where(d=>d.ReinspectionName.Contains(request.ReinspectionName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ReinspectionCode))
            {
                ReList = ReList.Where(d => d.ReinspectionCode.Contains(request.ReinspectionCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ReinspectionSarte))
            {
                ReList = ReList.Where(d => d.ReinspectionSarte==request.ReinspectionSarte).ToList();
            }
            if (request.Pagesize == null)
            {
                request.Pagesize = ReList.Count();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }
            PageDto<Reinspection> page = new PageDto<Reinspection>();
            var size = request.Pagesize;
            var index = request.Pageindex;
            page.TotalCount = ReList.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)size);
            page.list = ReList.OrderByDescending(o => o.ReinspectionTime).Skip(((int)(index - 1)) * ((int)size)).Take((int)size).ToList();
            return page;

        }
    }
}
